import md5 from 'md5'
import axios from 'axios'
import qs from 'qs'
import { storage } from './storage'

axios.defaults.timeout = 60000
// axios.defaults.withCredentials = true
// axios.defaults.baseURL = 'http://api.zbeiw.com/api'
axios.defaults.baseURL =  process.env.HTTP_BASE_API

// 设置默认请求头
axios.defaults.headers = {
  'Content-type': 'application/json'
}

// 序列化参数
axios.defaults.transformRequest = (data) => {
  data.formData = false
  if (data.formData) {
    data.formData = undefined
    data = qs.stringify(data) // 表单数据
  } else {
    data = JSON.stringify(data) // json 数据
  }
  return data
}

let cancel = {}
let promiseArr = []
const CancelToken = axios.CancelToken

// http request 拦截器
axios.interceptors.request.use(
  config => {
    // 发起请求时，取消掉当前正在进行的相同请求
    let url = config.url || ''
    let hasCancel = false
    promiseArr.forEach(item => {
      if (item.url === url) {
        item.cancel('操作取消')
        item.cancel = cancel
        hasCancel = true
      }
    })

    if (!hasCancel) {
      promiseArr.push({
        url, cancel
      })
    }

    // config.headers['clientId'] = storage.get("clientId");
    
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error) {
      return '请求失败'
    }
    return Promise.reject(error)
  }
)

// http 请求
const request = (method, url, param) => {
  return new Promise((resolve, reject) => {
    if (!param) {
      param = {}
    }
    axios({
      method,
      url,
      data: method !== 'get' ? param : {},
      params: method === 'get' ? param : {},
      cancelToken: new CancelToken(c => {
        cancel = c
      })
    }).then(res => {
      resolve(res)
    }).catch(error => {
      reject(error)
    })
  })
}

export const http = {
  // get请求
  async get(url, param) {
    return request('get', url, param)
  },
  // post请求
  async post(url, param) {
    return request('post', url, param)
  },
  // put请求
  async put(url, param) {
    return request('put', url, param)
  },
  // delete请求
  async delete(url, param) {
    return request('delete', url, param)
  }
}
